<template>
  <Layout>
    <Form ref="form1" :model="form1" :label-width="120">
      <Row :gutter="16" class="query-form">
        <i-col span="8">
          <FormItem label="二级集团：">
            <Select
              v-model="form1.twoLevelCompanyName"
              placeholder="请选择二级集团"
            >
              <Option
                v-for="(option, index) in twoLevelCompanyList"
                :value="option.orgName"
                :key="index"
              >
                {{ option.orgName }}
              </Option>
            </Select>
          </FormItem>
        </i-col>
        <Col span="8">
          <FormItem label="单位名称：" prop="companyName">
            <Input
              class="query-form-el"
              type="text"
              v-model="form1.companyName"
            ></Input>
          </FormItem>
        </Col>
        <Col span="8" v-if="!switchFlag">
          <Button @click="switchQuery(true)" class="ivu-btn-switch" type="text"
            >展开∨</Button
          >
          <Button
            class="ivu-btn-reset"
            style="margin-left: 10px"
            @click="cancel"
            >重置</Button
          >
          <Button class="ivu-btn-query" icon="md-search" @click="query1"
            >查询</Button
          >
        </Col>
        <i-col span="8" v-else>
          <FormItem label="年份：">
            <DatePicker
              class="query-form-el"
              type="year"
              placeholder="请选择年度"
              v-model="form1.year"
              :clearable="false"
              @on-change="
                () => {
                  if (form1.year instanceof Date) {
                    form1.year = form1.year.getFullYear().toString();
                  }
                }
              "
            ></DatePicker>
          </FormItem>
        </i-col>
      </Row>
      <Row :gutter="16" class="query-form" v-show="switchFlag">
        <i-col span="8">
          <FormItem label="季度：" prop="quarter">
            <Select v-model="form1.quarter" placeholder="请选择季度">
              <Option
                v-for="(option, index) in quarterList"
                :value="option.value"
                :key="index"
                >{{ option.label }}
              </Option>
            </Select>
          </FormItem>
        </i-col>
        <i-col span="8">
          <FormItem label="状态：">
            <Select v-model="form1.status" placeholder="请选择">
              <Option value="1">已登记</Option>
              <Option value="2">未登记</Option>
            </Select>
          </FormItem>
        </i-col>
        <Col span="8">
          <Button @click="switchQuery(false)" class="ivu-btn-switch" type="text"
            >收起∧</Button
          >
          <Button
            class="ivu-btn-reset"
            style="margin-left: 10px"
            @click="cancel"
            >重置</Button
          >
          <Button class="ivu-btn-query" icon="md-search" @click="query1"
            >查询</Button
          >
        </Col>
      </Row>
      <Row class="query-form">
        <Col span="24">
          <Button size="large" class="ivu-btn-add" @click="importModalShow"
            >导入</Button
          >
          <Button
            size="large"
            :loading="buttonLoading"
            class="ivu-btn-add"
            icon="md-cloud-download"
            @click="exportTemplateDatas"
            >导出
          </Button>
        </Col>
      </Row>
    </Form>

    <Table
      ref="table"
      :height="tableHeight"
      :loading="loading"
      @on-selection-change="getSelectRows"
      @on-sort-change="sortChange"
      border
      :columns="columns1"
      :data="dataTable"
    >
    </Table>

    <Row style="margin-right:10px;">
      <Col span="24">
        <Page
          style="float: right"
          :total="pagedata.total"
          :page-size="pagedata.pageSize"
          @on-change="pageChange"
          @on-page-size-change="pageSizeChange"
          :page-size-opts="pageSizeArray"
          show-total
          show-sizer
          show-elevator
        />
      </Col>
    </Row>

    <Modal
      :title="title"
      :transfer="false"
      :mask-closable="false"
      v-model="model1"
      :width="1200"
    >
      <Row>
        <Col span="24">
          <Form ref="form1datacopy" :model="form1datacopy" label-position="top">
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="23">
                <FormItem label="单位名称：" prop="companyName">
                  <Input
                    type="text"
                    v-model="form1datacopy.companyName"
                  ></Input>
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label="法人代码：" prop="legalEntityCode">
                  <Input
                    type="text"
                    v-model="form1datacopy.legalEntityCode"
                  ></Input>
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label="三证合一代码：" prop="threeCertificate">
                  <Input
                    type="text"
                    v-model="form1datacopy.threeCertificate"
                  ></Input>
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label="号牌号码：" prop="carNumber">
                  <Input type="text" v-model="form1datacopy.carNumber"></Input>
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label="号牌种类：" prop="numberType">
                  <Input type="text" v-model="form1datacopy.numberType"></Input>
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label="当事人：" prop="party">
                  <Input type="text" v-model="form1datacopy.party"></Input>
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label="信息来源：" prop="informationSources">
                  <Input
                    type="text"
                    v-model="form1datacopy.informationSources"
                  ></Input>
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label="违法记分数：" prop="illegalTime">
                  <Input
                    type="text"
                    v-model="form1datacopy.illegalScore"
                  ></Input>
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label="违法时间：" prop="illegalTime">
                  <Input
                    type="text"
                    v-model="form1datacopy.illegalTime"
                  ></Input>
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label="违法地址：" prop="illegalAddress">
                  <Input
                    type="text"
                    v-model="form1datacopy.illegalAddress"
                  ></Input>
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label="违法内容：" prop="illegalContent">
                  <Input
                    type="text"
                    v-model="form1datacopy.illegalContent"
                  ></Input>
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label="发现机关：" prop="discoveryMechanism">
                  <Input
                    type="text"
                    v-model="form1datacopy.discoveryMechanism"
                  ></Input>
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label="使用性质：" prop="natureOfUse">
                  <Input
                    type="text"
                    v-model="form1datacopy.natureOfUse"
                  ></Input>
                </FormItem>
              </Col>
            </Row>
          </Form>
        </Col>
      </Row>
      <div slot="footer">
        <Button
          @click="submit('form1datacopy')"
          class="ivu-btn-save"
          :loading="buttonLoading"
          >确定</Button
        >
        <Button @click="handleCancel" class="ivu-btn-cancel">取消</Button>
      </div>
    </Modal>
    <Modal
      title="主题详情"
      class="modal-view-detail"
      :transfer="false"
      v-model="model2"
      :width="800"
    >
      <Row>
        <Col span="24">
          <Form :model="showdata" :label-width="120">
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="23">
                <FormItem label="单位名称：" prop="companyName">
                  {{ showdata.companyName }}
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label="法人代码：" prop="legalEntityCode">
                  {{ showdata.legalEntityCode }}
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label="三证合一代码：" prop="threeCertificate">
                  {{ showdata.threeCertificate }}
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label="号牌号码：" prop="carNumber">
                  {{ showdata.carNumber }}
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label="号牌种类：" prop="numberType">
                  {{ showdata.numberType }}
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label="当事人：" prop="party">
                  {{ showdata.party }}
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label="违法时间：" prop="illegalTime">
                  {{ showdata.illegalTime }}
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label="违法地址：" prop="illegalAddress">
                  {{ showdata.illegalAddress }}
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label="违法内容：" prop="illegalContent">
                  {{ showdata.illegalContent }}
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label="发现机关：" prop="discoveryMechanism">
                  {{ showdata.discoveryMechanism }}
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label="使用性质：" prop="natureOfUse">
                  {{ showdata.natureOfUse }}
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label="信息来源：" prop="informationSources">
                  {{ showdata.informationSources }}
                </FormItem>
              </Col>
              <Col span="11"> </Col>
            </Row>
          </Form>
        </Col>
      </Row>
      <div slot="footer">
        <Button class="ivu-btn-save" @click="model2 = false">关闭</Button>
      </div>
    </Modal>

    <Modal v-model="importModal" :width="1400" title="导入">
      <Form
        ref="pageModel2"
        :model="pageModel2"
        :label-width="120"
        :rules="ruleCustom"
      >
        <Row class="query-form">
          <Col span="8">
            <FormItem label="年份：" prop="year">
              <Date-picker
                v-model="pageModel2.year"
                type="year"
                placeholder="选择年份"
                style="width: 200px"
              ></Date-picker>
            </FormItem>
          </Col>
          <Col span="8">
            <FormItem label="季度：" prop="quarter">
              <Select v-model="pageModel2.quarter" placeholder="请选择季度">
                <Option
                  v-for="(option, index) in quarterList"
                  :value="option.value"
                  :key="index"
                  >{{ option.label }}
                </Option>
              </Select>
            </FormItem>
          </Col>
          <Col span="8">
            <Upload
              style="margin-left:30px"
              action=""
              :format="['xlsx']"
              :before-upload="importInfo"
            >
              <Button class="ivu-btn-query" icon="ios-cloud-upload-outline"
                >上传文件</Button
              >
            </Upload>
          </Col>
        </Row>
        <Row>
          <Col span="24">
            <Tabs value="name1">
              <Tab-pane label="系统单位详情" name="name1">
                <Table
                  height="400"
                  no-data-text="没有查询到相关数据!"
                  size="small"
                  :loading="loading"
                  highlight-row
                  stripe
                  border
                  :columns="columns3"
                  width="100%"
                  :data="companyDetailDatas"
                >
                </Table>
              </Tab-pane>
              <Tab-pane label="现场违法记录" name="name2">
                <Table
                  height="400"
                  no-data-text="没有查询到相关数据!"
                  size="small"
                  :loading="loading"
                  highlight-row
                  stripe
                  border
                  :columns="columns2"
                  width="100%"
                  :data="siteDatas"
                >
                </Table>
              </Tab-pane>
              <Tab-pane label="非现场违法记录" name="name3">
                <Table
                  height="400"
                  no-data-text="没有查询到相关数据!"
                  size="small"
                  :loading="loading"
                  highlight-row
                  stripe
                  border
                  :columns="columns4"
                  width="100%"
                  :data="notSiteDatas"
                >
                </Table>
              </Tab-pane>
            </Tabs>
          </Col>
        </Row>
      </Form>
      <div slot="footer">
        <Button
          class="ivu-btn-save"
          :loading="buttonLoading"
          @click="saveTemplateDatas"
          >保存</Button
        >
        <Button class="ivu-btn-cancel" @click="onCancelByTemplate">取消</Button>
      </div>
    </Modal>
  </Layout>
</template>

<script>
import orgCascaderDom from "../../../../components/cascader-dom.vue";
import { sessionStorage } from "../../../../common/cacheUtils.js";
import { Api } from "../../../../api/index.js";

export default {
  components: {
    orgCascaderDom,
  },
  data() {
    return {
      companyDetailDatas: [],
      siteDatas: [],
      notSiteDatas: [],
      tempCompanyDetailDatas: [],
      tempSiteDatas: [],
      tempNotSiteDatas: [],
      se_date: [],
      year: "",
      quarter: "",
      pageModel2: {
        year: "",
        quarter: "",
      },
      loading2: false,
      importModal: false,
      exportModal: false,
      model3: false,
      buttonLoading: false,
      loading: false,
      title: "",
      saveMod: false,
      switchFlag: false,
      form1: {},
      setCurrentName: {},
      companyNameWithTwoLevelInfoMap: {},
      twoLevelCompanyMap: {},
      //分页参数
      pageSizeArray: [10, 20, 50],
      pagedata: {
        total: 0,
        pageSize: 10,
        currentPage: 1,
        total1: 0,
        pageSize1: 10,
        currentPage1: 1,
        total2: 0,
        pageSize2: 10,
        currentPage2: 1,
        total3: 0,
        pageSize3: 10,
        currentPage3: 1,
      },
      quarterList: [
        { value: "一", label: "一季度" },
        { value: "二", label: "二季度" },
        { value: "三", label: "三季度" },
        { value: "四", label: "四季度" },
      ],
      currentUserId: sessionStorage("userId").getObject("userId").userId,
      currentUser: JSON.parse(sessionStorage("userId").get("userId")),
      columns1: [
        {
          title: "序号",
          width: 80,
          align: "center",
          fixed: "left",
          render: (h, params) => {
            return h(
              "span",
              params.index +
                (this.pagedata.currentPage - 1) * this.pagedata.pageSize +
                1
            );
          },
        },
        {
          minWidth: 300,
          title: "二级单位名称",
          align: "center",
          key: "twoLevelCompanyName",
        },
        {
          minWidth: 300,
          title: "单位名称",
          align: "center",
          key: "companyName",
        },
        {
          minWidth: 120,
          title: "状态",
          align: "center",
          key: "companyId",
          render: (h, params) => {
            return h("div", [params.row.companyId == null ? "未登记" : "登记"]);
          },
        },
        {
          minWidth: 120,
          title: "号牌号码",
          align: "center",
          key: "carNumber",
        },
        {
          minWidth: 120,
          title: "号牌种类",
          align: "center",
          key: "numberType",
        },
        {
          minWidth: 100,
          title: "当事人",
          align: "center",
          key: "party",
        },
        {
          minWidth: 150,
          title: "违法时间",
          sortable: "custom",
          align: "center",
          key: "illegalTime",
          render: (h, params) => {
            return h("div", [
              this.formatDate(new Date(params.row.illegalTime), "yyyy-MM-dd"),
            ]);
          },
        },
        {
          minWidth: 100,
          title: "违法记分数",
          align: "center",
          key: "illegalScore",
        },
        {
          minWidth: 150,
          title: "违法地址",
          align: "center",
          key: "illegalAddress",
        },
        {
          minWidth: 150,
          title: "违法内容",
          align: "center",
          key: "illegalContent",
          tooltip: true,
        },
        {
          minWidth: 150,
          title: "发现机关",
          align: "center",
          key: "discoveryMechanism",
        },
        {
          minWidth: 150,
          title: "使用性质",
          align: "center",
          key: "natureOfUse",
        },
        {
          minWidth: 150,
          title: "信息来源",
          align: "center",
          key: "informationSources",
        },
        {
          title: "操作",
          key: "action",
          fixed: "right",
          minWidth: 200,
          align: "center",
          render: (h, params) => {
            let flag =
              this.currentUser.loginId === this.Common.admin ||
              this.currentUser.userId === params.row.createUserId ||
              this.currentUser.companyId === "18000000" ||
              (this.currentUser.userRole.find(
                (obj) => obj.roleId == "73b38b37dff64392ba0ee7dd579bf293"
              ) != undefined &&
                params.row.orgCode &&
                params.row.orgCode.indexOf(this.currentUser.companyCode) != -1);
            return h("div", [
              h(
                "A",
                {
                  props: {
                    type: "primary",
                    size: "small",
                  },
                  style: {
                    fontSize: "14px",
                  },
                  on: {
                    style: {
                      fontSize: "14px",
                      color: flag ? "" : "#c5c8ce",
                      pointerEvents: flag ? "" : "none",
                    },
                    click: () => {
                      this.showData(params, 1);
                    },
                  },
                },
                "详情"
              ),
              h(
                "Divider",
                {
                  props: {
                    type: "vertical",
                  },
                },
                ""
              ),
              h(
                "A",
                {
                  props: {
                    type: "primary",
                    size: "small",
                  },
                  style: {
                    fontSize: "14px",
                    color: flag ? "red" : "#c5c8ce",
                    pointerEvents: flag ? "" : "none",
                  },
                  on: {
                    click: () => {
                      this.showData(params, 2);
                    },
                  },
                },
                "修改"
              ),
              h(
                "Divider",
                {
                  props: {
                    type: "vertical",
                  },
                },
                ""
              ),
              h(
                "A",
                {
                  props: {
                    type: "primary",
                    size: "small",
                  },
                  style: {
                    fontSize: "14px",
                    color: flag ? "red" : "#c5c8ce",
                    pointerEvents: flag ? "" : "none",
                  },
                  on: {
                    click: () => {
                      this.$Modal.confirm({
                        title: "数据删除",
                        content: "<p>确定删除该条信息</p>",
                        okText: "确认",
                        onOk: () => {
                          this.deleteData(params);
                        },
                        cancelText: "取消",
                      });
                    },
                  },
                },
                "删除"
              ),
            ]);
          },
        },
      ],
      columns2: [
        {
          title: "序号",
          width: 80,
          align: "center",
          fixed: "left",
          render: (h, params) => {
            return h("span", params.index + 1);
          },
        },
        {
          minWidth: 350,
          title: "二级集团名称",
          align: "center",
          key: "twoLevelCompanyName",
          render: (h, params) => {
            return h("div", [
              h(
                "Select",
                {
                  props: {
                    //属性
                    value: params.row.twoLevelCompanyName,
                    transfer: true,
                  },
                  on: {
                    // 改变事件
                    "on-change": (value) => {
                      this.siteDatas[params.index].secondCompanyName = value;
                      this.siteDatas[params.index].twoLevelCompanyName = value;
                    },
                  },
                }, // 下拉项数据赋值
                this.twoLevelCompanyList.map((obj) => {
                  return h("Option", {
                    props: { value: obj.orgName, label: obj.orgName },
                  });
                })
              ),
            ]);
          },
        },
        {
          minWidth: 350,
          title: "二级单位名称",
          align: "center",
          key: "secondCompanyName",
        },
        {
          minWidth: 350,
          title: "单位名称",
          align: "center",
          key: "companyNameChoose",
          render: (h, params) => {
            return h("div", [
              h(orgCascaderDom, {
                props: {
                  //属性
                  rootOrgId: "18000000",
                  orgTree: true,
                },
                on: {
                  setOrgname: (value) => {
                    this.siteDatas[
                      params.index
                    ].companyNameChoose = value;
                    this.siteDatas[
                      params.index
                    ].companyName = value;
                  },
                },
              }),
            ]);
          },
        },
        {
          minWidth: 250,
          title: "单位名称",
          align: "center",
          key: "companyName",
        },
        {
          minWidth: 300,
          title: "法人代码",
          align: "center",
          key: "legalEntityCode",
        },
        {
          minWidth: 150,
          title: "三证合一代码",
          align: "center",
          key: "threeCertificate",
        },
        {
          minWidth: 150,
          title: "号牌号码",
          align: "center",
          key: "carNumber",
        },
        {
          minWidth: 150,
          title: "号牌种类",
          align: "center",
          key: "numberType",
        },
        {
          minWidth: 150,
          title: "当事人",
          align: "center",
          key: "party",
        },
        {
          minWidth: 150,
          title: "违法时间",
          align: "center",
          key: "illegalTime",
          render: (h, params) => {
            return h("div", [
              this.formatDate(new Date(params.row.illegalTime), "yyyy-MM-dd"),
            ]);
          },
        },
        {
          minWidth: 150,
          title: "违法地址",
          align: "center",
          key: "illegalAddress",
        },
        {
          minWidth: 150,
          title: "违法内容",
          align: "center",
          key: "illegalContent",
        },
        {
          minWidth: 150,
          title: "违法记分数",
          align: "center",
          key: "illegalScore",
        },
        {
          minWidth: 150,
          title: "发现机关",
          align: "center",
          key: "discoveryMechanism",
        },
        {
          minWidth: 150,
          title: "使用性质",
          align: "center",
          key: "natureOfUse",
        },
        {
          minWidth: 150,
          title: "信息来源",
          align: "center",
          key: "informationSources",
        },
      ],
      columns4: [
        {
          title: "序号",
          width: 80,
          align: "center",
          fixed: "left",
          render: (h, params) => {
            return h("span", params.index + 1);
          },
        },
        {
          minWidth: 350,
          title: "二级集团名称",
          align: "center",
          key: "twoLevelCompanyName",
          render: (h, params) => {
            return h("div", [
              h(
                "Select",
                {
                  props: {
                    //属性
                    value: params.row.twoLevelCompanyName,
                    transfer: true,
                  },
                  on: {
                    // 改变事件
                    "on-change": (value) => {
                      this.notSiteDatas[
                        params.index
                      ].secondCompanyName = value;
                    },
                  },
                }, // 下拉项数据赋值
                this.twoLevelCompanyList.map((obj) => {
                  return h("Option", {
                    props: { value: obj.orgName, label: obj.orgName },
                  });
                })
              ),
            ]);
          },
        },
        {
          minWidth: 350,
          title: "二级单位名称",
          align: "center",
          key: "secondCompanyName",
        },
        {
          minWidth: 350,
          title: "单位名称",
          align: "center",
          key: "companyNameChoose",
          render: (h, params) => {
            return h("div", [
              h(orgCascaderDom, {
                props: {
                  //属性
                  rootOrgId: "18000000",
                  orgTree: true,
                },
                on: {
                  setOrgname: (value) => {
                    this.notSiteDatas[
                      params.index
                    ].companyNameChoose = value;
                    this.notSiteDatas[
                      params.index
                    ].companyName = value;
                  },
                },
              }),
            ]);
          },
        },
        {
          minWidth: 250,
          title: "单位名称",
          align: "center",
          key: "companyName",
        },
        {
          minWidth: 300,
          title: "法人代码",
          align: "center",
          key: "legalEntityCode",
        },
        {
          minWidth: 150,
          title: "三证合一代码",
          align: "center",
          key: "threeCertificate",
        },
        {
          minWidth: 150,
          title: "号牌号码",
          align: "center",
          key: "carNumber",
        },
        {
          minWidth: 150,
          title: "号牌种类",
          align: "center",
          key: "numberType",
        },
        {
          minWidth: 150,
          title: "当事人",
          align: "center",
          key: "party",
        },
        {
          minWidth: 150,
          title: "违法时间",
          align: "center",
          key: "illegalTime",
          render: (h, params) => {
            return h("div", [
              this.formatDate(new Date(params.row.illegalTime), "yyyy-MM-dd"),
            ]);
          },
        },
        {
          minWidth: 150,
          title: "违法地址",
          align: "center",
          key: "illegalAddress",
        },
        {
          minWidth: 150,
          title: "违法内容",
          align: "center",
          key: "illegalContent",
        },
        {
          minWidth: 150,
          title: "违法记分数",
          align: "center",
          key: "illegalScore",
        },
        {
          minWidth: 150,
          title: "发现机关",
          align: "center",
          key: "discoveryMechanism",
        },
        {
          minWidth: 150,
          title: "使用性质",
          align: "center",
          key: "natureOfUse",
        },
        {
          minWidth: 150,
          title: "信息来源",
          align: "center",
          key: "informationSources",
        },
      ],
      columns3: [
        {
          title: "序号",
          width: 80,
          align: "center",
          fixed: "left",
          render: (h, params) => {
            return h("span", params.index + 1);
          },
        },
        {
          minWidth: 350,
          title: "二级集团名称",
          align: "center",
          key: "twoLevelCompanyName",
          render: (h, params) => {
            return h("div", [
              h(
                "Select",
                {
                  props: {
                    //属性
                    value: params.row.companyNameChoose,
                    transfer: true,
                  },
                  on: {
                    // 改变事件
                    "on-change": (value) => {
                      this.companyDetailDatas[
                        params.index
                      ].companyNameChoose = value;
                      this.companyDetailDatas[params.index].companyName = value;
                    },
                  },
                }, // 下拉项数据赋值
                this.twoLevelCompanyList.map((obj) => {
                  return h("Option", {
                    props: { value: obj.orgName, label: obj.orgName },
                  });
                })
              ),
            ]);
          },
        },
        {
          minWidth: 350,
          title: "二级集团名称",
          align: "center",
          key: "secondCompanyName",
        },
        {
          minWidth: 350,
          title: "单位名称",
          align: "center",
          key: "companyNameChoose",
          render: (h, params) => {
            return h("div", [
              h(orgCascaderDom, {
                props: {
                  //属性
                  rootOrgId: "18000000",
                  orgTree: true,
                },
                on: {
                  setOrgname: (value) => {
                    this.companyDetailDatas[
                      params.index
                    ].companyNameChoose = value;
                    this.companyDetailDatas[
                      params.index
                    ].companyName = value;
                  },
                },
              }),
            ]);
          },
        },
        {
          minWidth: 250,
          title: "单位名称",
          align: "center",
          key: "companyName",
        },
        {
          minWidth: 300,
          title: "法人代码",
          align: "center",
          key: "legalEntityCode",
        },
        {
          minWidth: 150,
          title: "三证合一代码",
          align: "center",
          key: "threeCertificate",
        },
        {
          minWidth: 150,
          title: "车辆数",
          align: "center",
          key: "trafficNumber",
        },
        {
          minWidth: 150,
          title: "现场违法数",
          align: "center",
          key: "numberOnSiteViolation",
        },
        {
          minWidth: 150,
          title: "非现场违法数",
          align: "center",
          key: "numberNotOnSiteViolation",
        },
        {
          minWidth: 150,
          title: "违法总数",
          align: "center",
          key: "numberViolation",
          render: (h, params) => {
            return h("div", [
              Number(params.row.numberOnSiteViolation) +
                Number(params.row.numberNotOnSiteViolation),
            ]);
          },
        },
        {
          minWidth: 150,
          title: "违法率",
          align: "center",
          key: "illegalRate",
          render: (h, params) => {
            return h("div", [
              ((Number(params.row.numberOnSiteViolation) +
                Number(params.row.numberNotOnSiteViolation)) *
                100) /
                params.row.trafficNumber +
                "%",
            ]);
          },
        },
      ],
      safeDataByTemplate: [],
      ruleCustom: {
        year: [
          {
            required: true,
            message: "  ",
            trigger: "change",
            type: "date",
          },
        ],
        quarter: [
          {
            required: true,
            message: "  ",
            trigger: "blur",
          },
        ],
      },
      form1datacopy: {
        fillInTime: ["", ""],
        execlSheet: "{}",
      },
      dataTable: [],
      showdata: {},
      model1: false,
      model2: false,
      add: false,
      tableHeight: 10,
      themeList: [],
      twoLevelCompanyList: [],
    };
  },
  mounted: function() {
    this.tableHeight =
      window.innerHeight - this.$refs.table.$el.offsetTop - 145;
    this.getTwoLevelCompanyList();
    this.getCompanyNameWithTwoLevelInfo();
    this.query();
  },
  methods: {
    sortChange(data) {
      if (data.order === "asc" || data.order === "desc") {
        let order = data.key;
        this.form1.dynamicSort = order + " " + data.order;
        this.query();
      }
    },
    switchQuery(flag) {
      this.switchFlag = flag;
      if (this.switchFlag) {
        this.tableHeight = this.tableHeight - 44;
      } else {
        this.tableHeight = this.tableHeight + 44;
      }
    },
    setUserName(data) {
      this.form1.userName = data;
    },
    setUserId(data) {
      this.form1.staff = data[data.length - 1];
    },
    pageChange(pageNum) {
      this.pagedata.currentPage = pageNum;
      this.query();
    },
    pageSizeChange(pageSize) {
      this.pagedata.pageSize = pageSize;
      this.query();
    },
    pageChange1(pageNum) {
      this.pagedata.currentPage1 = pageNum;
      this.tempCompanyDetailDatas = this.companyDetailDatas.slice(
        (this.pagedata.currentPage1 - 1) ** this.pagedata.pageSize1,
        (this.pagedata.currentPage1 + 1) * this.pagedata.pageSize1
      );
    },
    pageSizeChange1(pageSize) {
      this.pagedata.pageSize1 = pageSize;
      this.tempCompanyDetailDatas = this.companyDetailDatas.slice(
        (this.pagedata.currentPage1 - 1) * this.pagedata.pageSize1,
        (this.pagedata.currentPage1 + 1) * this.pagedata.pageSize1
      );
    },
    pageChange2(pageNum) {
      this.pagedata.currentPage2 = pageNum;
      this.tempSiteDatas = this.siteDatas.slice(
        (this.pagedata.currentPage2 - 1) * this.pagedata.pageSize2,
        this.pagedata.currentPage2 * this.pagedata.pageSize2
      );
    },
    pageSizeChange2(pageSize) {
      this.pagedata.pageSize2 = pageSize;
      this.tempSiteDatas = this.siteDatas.slice(
        (this.pagedata.currentPage2 - 1) * this.pagedata.pageSize2,
        this.pagedata.currentPage2 * this.pagedata.pageSize2
      );
    },
    pageChange3(pageNum) {
      this.pagedata.currentPage3 = pageNum;
      this.tempNotSiteDatas = this.notSiteDatas.slice(
        (this.pagedata.currentPage3 - 1) * this.pagedata.pageSize3,
        this.pagedata.currentPage3 * this.pagedata.pageSize3
      );
    },
    pageSizeChange3(pageSize) {
      this.pagedata.pageSize3 = pageSize;
      this.tempNotSiteDatas = this.notSiteDatas.slice(
        (this.pagedata.currentPage3 - 1) * this.pagedata.pageSize3,
        this.pagedata.currentPage3 * this.pagedata.pageSize3
      );
    },
    cancel() {
      this.se_date = [];
      this.form1 = {};
      this.query1();
    },
    copyArray(arr) {
      return JSON.parse(JSON.stringify(arr));
    },
    showData(data, flag) {
      this.buttonLoading = false;
      if (flag == 1) {
        //查看页面
        this.showdata = data.row;
        if (this.showdata.createDate != null) {
          this.showdata.createDateStr = this.formatDate(
            new Date(this.showdata.createDate),
            "yyyy-MM-dd"
          );
        }
        if (this.showdata.startDate != null) {
          this.showdata.startDateStr = this.formatDate(
            new Date(this.showdata.startDate),
            "yyyy-MM-dd"
          );
        }
        if (this.showdata.endDate != null) {
          this.showdata.endDateStr = this.formatDate(
            new Date(this.showdata.endDate),
            "yyyy-MM-dd"
          );
        }
        this.model2 = true;
      } else {
        this.title = "主题修改";
        this.saveMod = false;
        this.add = false;
        this.form1datacopy = data.row;
        this.form1datacopy = JSON.parse(JSON.stringify(data.row));
        if (this.form1datacopy.startDate != null) {
          this.form1datacopy.fillInTime = [
            this.formatDate(
              new Date(this.form1datacopy.startDate),
              "yyyy-MM-dd"
            ),
            this.formatDate(new Date(this.form1datacopy.endDate), "yyyy-MM-dd"),
          ];
        }
        this.model1 = true;
      }
    },
    getSelectRows(rows) {
      this.deleteRows = rows;
    },
    deleteData(params) {
      let url = Api.deleteTrafficBreakRaw;
      this.$http
        .delete(url + "/" + params.row.id)
        .then((res) => {
          this.$Message.success("成功");
          this.query();
        })
        .catch((e) => {
          this.$Message.error("请求失败" + e);
        });
    },
    query1() {
      this.pagedata.currentPage = 1;
      this.query();
    },
    query() {
      this.loading = true;
      let data = {
        startPage: this.pagedata.currentPage,
        size: this.pagedata.pageSize,
      };
      if (this.se_date.length != 0) {
        if (this.se_date[0] != "" && this.se_date[1] != "") {
          data.illegalStartTime = this.formatDate(
            new Date(this.se_date[0]),
            "yyyy-MM-dd"
          );
          data.illegalEndTime = this.formatDate(
            new Date(this.se_date[1]),
            "yyyy-MM-dd"
          );
        }
      }
      data = Object.assign(data, JSON.parse(JSON.stringify(this.form1)));
      let url = Api.trafficBreakRawList;
      this.$http
        .get(url, {
          params: data,
        })
        .then((res) => {
          this.loading = false;
          this.dataTable = res.data.data.data;
          this.pagedata.total = res.data.data.totalSize;
        })
        .catch((e) => {
          this.$Message.error("数据获取失败");
        });
    },
    getTwoLevelCompanyList() {
      this.$http
        .get(Api.twoLevelCompanyList)
        .then((res) => {
          if (res.status == 200) {
            this.twoLevelCompanyList = res.data.data;
            this.twoLevelCompanyList.forEach((item) => {
              this.twoLevelCompanyMap[item.orgName] = item.orgId;
            });
          }
        })
        .catch((e) => {
          this.$Message.error("数据获取失败");
        });
    },
    getCompanyNameWithTwoLevelInfo() {
      this.$http
        .get(Api.companyNameWithTwoLevelInfo)
        .then((res) => {
          if (res.status == 200) var datas = res.data.data;
          datas.forEach((item) => {
            this.companyNameWithTwoLevelInfoMap[item.companyName] =
              item.twoLevelCompanyName;
          });
        })
        .catch((e) => {
          this.$Message.error("数据获取失败");
        });
    },
    reset() {
      this.se_date = ["", ""];
      this.form1 = {};
      setTimeout(() => {
        this.$refs.childUser.setCurrentUser();
      }, 50);
    },
    handleCancel() {
      this.form1datacopy = {};
      this.model1 = false;
    },
    exportModalShow() {
      this.year = "";
      this.quarter = "";
      this.exportModal = true;
    },
    importModalShow() {
      this.siteDatas = [];
      this.notSiteDatas = [];
      this.companyDetailDatas = [];
      this.tempSiteDatas = [];
      this.tempNotSiteDatas = [];
      this.tempCompanyDetailDatas = [];
      this.pageModel2 = {
        year: "",
        quarter: "",
      };
      this.pagedata.currentPage1 = 0;
      this.pagedata.total1 = 0;
      this.pagedata.currentPage2 = 0;
      this.pagedata.total2 = 0;
      this.pagedata.currentPage3 = 0;
      this.pagedata.total3 = 0;
      this.importModal = true;
      this.loading = false;
    },
    onCancelByTemplate() {
      this.importModal = false;
      this.loading = false;
    },
    importInfo(e) {
      var vali = /\.(xls|xlsx)$/;
      if (!vali.test(e.name.toLowerCase())) {
        this.$Message.error("上传格式不正确，请上传xls或者xlsx格式");
        return false;
      }
      this.loading = true;
      const fileReader = new FileReader();
      let this_ = this;
      fileReader.onload = function(e1) {
        try {
          this_.companyDetailDatas = [];
          this_.siteDatas = [];
          this_.notSiteDatas = [];
          const data1 = e1.target.result; // data则是我们在excel表中获取的数据
          var XLSX = require("xlsx");
          const Workbook = XLSX.read(data1, { type: "binary" }); // 通过XLSX读取出来得到了一个 workdata 对象，下面详细介绍 workdata 对象中有些什么
          let workSheet = Workbook.Sheets[Workbook.SheetNames[0]];
          const execlDatas = XLSX.utils.sheet_to_json(workSheet);
          for (var i = 0; i < execlDatas.length; i++) {
            var execlData = execlDatas[i];
            var obj = {
              systemType: execlData["系统大类"],
              firstCompanyName: "北京金隅集团股份有限公司",
              secondCompanyName: execlData["二级单位名称"],
              twoLevelCompanyName: execlData["二级单位名称"],
              companyName:
                execlData["三级单位名称"] == "" ||
                execlData["三级单位名称"] == undefined
                  ? execlData["二级单位名称"]
                  : execlData["三级单位名称"],
              legalEntityCode: execlData["法人代码"],
              threeCertificate: execlData["三证合一代码"],
              trafficNumber: execlData["车辆数"],
              numberOnSiteViolation: execlData["现场违法数"],
              numberNotOnSiteViolation: execlData["非现场违法数"],
              createUserId: sessionStorage("userId").getObject("userId").userId,
              createDate: this_.formatDate(new Date(), "yyyy-MM-dd"),
            };
            if (
              obj.twoLevelCompanyName == "小计" ||
              obj.twoLevelCompanyName == "合计"
            ) {
              obj.companyName = "";
              obj.firstCompanyName = "";
            } else {
              if (
                obj.twoLevelCompanyName.charAt(
                  obj.twoLevelCompanyName.length - 1
                ) == "）"
              ) {
                let index = obj.twoLevelCompanyName.lastIndexOf("（");
                obj.twoLevelCompanyName = obj.twoLevelCompanyName.substr(
                  0,
                  index
                );
              }
              if (
                this_.companyNameWithTwoLevelInfoMap[obj.companyName] !=
                undefined
              )
                obj.twoLevelCompanyName =
                  this_.companyNameWithTwoLevelInfoMap[obj.companyName];
              if (
                obj.twoLevelCompanyName != "" &&
                obj.twoLevelCompanyName != undefined
              )
                obj.twoLevelCompanyId =
                  this_.twoLevelCompanyMap[obj.twoLevelCompanyName];
            }
            this_.companyDetailDatas.push(obj);
          }
          for (var w = 1; w < 3; w++) {
            let workSheet = Workbook.Sheets[Workbook.SheetNames[w]];
            const execlDatas = XLSX.utils.sheet_to_json(workSheet);
            for (var i = 0; i < execlDatas.length; i++) {
              var execlData = execlDatas[i];
              var obj = {
                systemType: execlData["系统大类"],
                secondCompanyName: execlData["二级单位名称"],
                twoLevelCompanyName: execlData["二级单位名称"],
                companyName:
                  execlData["三级单位名称"] == "" ||
                  execlData["三级单位名称"] == undefined
                    ? execlData["二级单位名称"]
                    : execlData["三级单位名称"],
                legalEntityCode: execlData["法人代码"],
                threeCertificate: execlData["三证合一代码"],
                carNumber: execlData["号牌号码"],
                numberType: execlData["号牌种类"],
                party: execlData["当事人"],
                illegalScore: execlData["违法记分数"],
                illegalTime: execlData["违法时间"],
                illegalAddress: execlData["违法地址"],
                illegalContent: execlData["违法内容"],
                discoveryMechanism: execlData["发现机关"],
                natureOfUse: execlData["使用性质"],
                informationSources: w == 1? "现场处罚":"非现场处罚",
                createUserId: sessionStorage("userId").getObject("userId")
                  .userId,
                createDate: this_.formatDate(new Date(), "yyyy-MM-dd"),
              };
              if (
                obj.twoLevelCompanyName.charAt(
                  obj.twoLevelCompanyName.length - 1
                ) == "）"
              ) {
                let index = obj.twoLevelCompanyName.lastIndexOf("（");
                obj.twoLevelCompanyName = obj.twoLevelCompanyName.substr(
                  0,
                  index
                );
              }
              if (
                this_.companyNameWithTwoLevelInfoMap[obj.companyName] !=
                undefined
              )
                obj.twoLevelCompanyName =
                  this_.companyNameWithTwoLevelInfoMap[obj.companyName];
              if (
                obj.twoLevelCompanyName != "" &&
                obj.twoLevelCompanyName != undefined
              )
                obj.twoLevelCompanyId =
                  this_.twoLevelCompanyMap[obj.twoLevelCompanyName];
              if (w == 1) {
                this_.siteDatas.push(obj);
              } else {
                this_.notSiteDatas.push(obj);
              }
            }
          }
          /*
          this_.pagedata.total1 = this_.companyDetailDatas.length;
          this_.pagedata.total2 = this_.siteDatas.length;
          this_.pagedata.total3 = this_.notSiteDatas.length;
          this_.tempCompanyDetailDatas = this_.companyDetailDatas.slice(this_.pagedata.currentPage1 * this_.pagedata.pageSize1, this_.pagedata.pageSize1);
          this_.tempSiteDatas = this_.siteDatas.slice(this_.pagedata.currentPage1 * this_.pagedata.pageSize1, this_.pagedata.pageSize1);
          this_.tempNotSiteDatas = this_.notSiteDatas.slice(this_.pagedata.currentPage1 * this_.pagedata.pageSize1, this_.pagedata.pageSize1);
     */
          this_.loading = false;
        } catch (e) {
          console.log(e);
          this_.$Message.error("请上传内容符合格式的execl文件");
          return false;
        }
      };
      fileReader.readAsBinaryString(e);
      return false;
    },
    saveTemplateDatas() {
      this.$refs["pageModel2"].validate((valid) => {
        if (valid) {
          this.buttonLoading = true;
          let aValid = true;
          let bValid = true;
          let cValid = true;
          for(let index = 0;index < this.siteDatas.length;index++){
            let item = this.siteDatas[index];
            if(item.illegalTime == null || item.illegalTime == '' || item.illegalTime == undefined){
              this.$Message.error("请补充现场违法数据中违法时间后重新导入");
              this.buttonLoading = false;
              return;
            }
            if(item.illegalScore == null || item.illegalScore == undefined){
              this.$Message.error("请补充现场违法数据中违法记分数后重新导入");
              this.buttonLoading = false;
              return;
            }
          }
          for(let index = 0;index < this.notSiteDatas.length;index++){
            let item = this.notSiteDatas[index];
            if(item.illegalTime == null || item.illegalTime == '' || item.illegalTime == undefined){
              this.$Message.error("请补充非现场违法数据中违法时间后重新导入");
              this.buttonLoading = false;
              return;
            }
            console.log(item)
            if(item.illegalScore == null ||  item.illegalScore == undefined){
              this.$Message.error("请补充非现场违法数据中违法记分数后重新导入");
              this.buttonLoading = false;
              return;
            }
          }
          var date = new Date(this.pageModel2.year);
          var formData = {
            companyDetail: this.companyDetailDatas,
            siteData: this.siteDatas,
            notSiteData: this.notSiteDatas,
            year: date.getFullYear(),
            quarter: this.pageModel2.quarter,
          };
          this.$http
            .post(Api.saveTrafficCompanyDetail, formData)
            .then((res) => {
              if(res.status == 200){
              this.$Message.success("保存成功");
              this.importModal = false;
              this.buttonLoading = false;
              this.query();
              }else{
                this.$Message.error("保存失败");
              }
            })
            .catch((e) => {
              this.importModal = false;
              this.buttonLoading = false;
              this.query();
              this.$Message.error("数据获取失败");
            });
        } else {
          this.$Message.error("请填写年份、季度信息");
        }
      });
    },
    exportTemplateDatas() {
      let _this = this;
      this.buttonLoading = true;
      let url = Api.exportBreakRawList;
      this.$http
        .get(url, { params: this.form1, responseType: "blob" })
        .then((res) => {
          const aLink = document.createElement("a");
          let blob = new Blob([res.data], {
            type: res.body.type, //将会被放入到blob中的数组内容的MIME类型
          });
          aLink.href = URL.createObjectURL(blob);
          if (
            this.form1.twoLevelCompanyName != undefined &&
            this.form1.twoLevelCompanyName != ""
          ) {
            aLink.download =
              this.form1.twoLevelCompanyName + "交通违法记录.xlsx";
          } else {
            aLink.download = "北京金隅集团股份有限公司交通违法记录.xlsx"; //标题
          }
          aLink.click();
          this.buttonLoading = false;
          this.exportModal = false;
          document.body.appendChild(aLink);
        });
    },
    addInfo() {
      this.title = "主题新增";
      this.saveMod = false;
      let orgName = sessionStorage("userId").getObject("userId").companyName;
      let userId = sessionStorage("userId").getObject("userId").userId;
      let userName = sessionStorage("userId").getObject("userId").userName;
      this.form1datacopy = {
        fillInTime: ["", ""],
        themeAddress: orgName,
        staff: userId,
        staffName: userName,
        execlSheet: "{}",
      };
      this.add = true;
      this.model1 = true;
    },
    exportExecl(params) {
      this.exportSheetExcel(
        JSON.parse(params.row.execlSheet),
        params.row.themeName + "--模板"
      );
    },
    importExecl() {},
    formatDate(date, fmt) {
      if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(
          RegExp.$1,
          (date.getFullYear() + "").substr(4 - RegExp.$1.length)
        );
      }
      let o = {
        "M+": date.getMonth() + 1,
        "d+": date.getDate(),
        "h+": date.getHours(),
        "m+": date.getMinutes(),
        "s+": date.getSeconds(),
      };
      for (let k in o) {
        if (new RegExp(`(${k})`).test(fmt)) {
          let str = o[k] + "";
          fmt = fmt.replace(
            RegExp.$1,
            RegExp.$1.length === 1 ? str : this.padLeftZero(str)
          );
        }
      }
      return fmt;
    },
    padLeftZero(str) {
      return ("00" + str).substr(str.length);
    },
  },
};
</script>
<style scoped>
@import "../../../../index.css";

.execlClass {
  width: 100%;
  height: 300px;
}
</style>
